/**
 * User: yeqingzhou01
 * Date: 13-9-6
 * Time: 下午11:38
 */
var util = require('util');
var dataSourceConfig = require('../../config/data-source-config');
var mongodb = require('mongodb');
var mongoose = require('mongoose');

var getDb = function(){
    var dbInfo = dataSourceConfig.mongo.dbInfo;
    var db = new mongodb.Db(
        dbInfo.dbName,
        new mongodb.Server(
            dbInfo.mongosList.host,
            dbInfo.mongosList.port
        )
    );
    return db;
}

/**
 * connect to database
 */
exports.connect = function () {
    var connectOptions = {
        mongos: true,
        replset: {
            poolSize: dataSourceConfig.mongo.systemConfig.connectionPoolSize
        }
//        server: {
//            poolSize: dataSourceConfig.mongo.systemConfig.connectionPoolSize
//        }
    }
    mongoose.connect(dataSourceConfig.mongo.db, connectOptions);
}
/**
 * disconnect from database
 * @param callback result of disconnect db
 */
exports.disconnect = function (callback) {
    mongoose.disconnect(callback);
}

/**
 * setup
 * @param callback
 */
exports.setup = function (callback) {
    callback(null);
}

var Schema = mongoose.Schema;
exports.Schema = Schema;

/**
 * Get basic dao class
 * @param collectionName
 * @param schemaObj
 * @returns {*}
 */
exports.getDaoClass = function (collectionName, schemaObj, options){
    if(!mongoose.models[collectionName]){
        mongoose.model(collectionName, new Schema(schemaObj, options));
    }
    return mongoose.model(collectionName);
}

/**
 * Get dao object with initialized object
 * @param collectionName
 * @param obj
 * @param schemaObj
 * @returns {Dao}
 */
exports.getDao = function (collectionName, obj, schemaObj) {
    var Dao = exports.getDaoClass(collectionName, schemaObj);
    return exports.getDaoWithClassAndObj(Dao, obj);
}

/**
 * Get DAO object with exist class and object
 * @param DaoClass
 * @param daoObj
 * @returns {DaoClass}
 */
exports.getDaoWithClassAndObj = function (DaoClass, daoObj) {
    var dao = new DaoClass();
    for(var onePropertyKey in daoObj){
        dao[onePropertyKey] = daoObj[onePropertyKey];
    }
    return dao;
}

exports.runScript = function(scriptCallback) {
    var db = getDb();
    db.open(function(err, db){
        scriptCallback(err, db);
    });
}